<template>
  <div>
    <div>
      <!--    搜索框-->
      <div class="mt-4">
        <el-input
            v-model="input"
            placeholder="在此输入想查询的信息"
            class="input-with-select"
            @input="filterSearch"
        >
          <template #prepend>
            <el-select v-model="select" placeholder="选择" style="width: 115px">
              <el-option label="名称" value="1" />
              <el-option label="编号" value="2" />
              <el-option label="种类" value="3" />
            </el-select>
          </template>
          <template #append>
            <el-button :icon="Search" />
          </template>
        </el-input>
        <!--      添加数据、批量删除-->
        <el-button type="primary" plain class="bt1" @click="handleAdd"><el-icon><CirclePlusFilled /></el-icon>添加商品</el-button>
        <el-button type="danger" plain @click="handleDelList" v-if="multipleSelection.length>0"><el-icon><RemoveFilled /></el-icon>批量删除</el-button>
        <el-button type="primary" :icon="FolderChecked" @click="handleExcel"
                   style="margin-left: 20px;">导出商品excel
        </el-button>
      </div>
    </div>
    <!--    表格-->
    <el-table
        ref="tableRef"
        row-key="productid"
        :data="tableData"
        style="width: 100%"
        @sort-change="handleSortChange"
        empty-text="暂无数据"
        @selection-change="handleSelectionChange"
    >
      <!--      选择列-->
      <el-table-column type="selection" width="60"></el-table-column>
      <!--      编号列-->
      <el-table-column prop="productid" label="编号" width="80" sortable></el-table-column>
      <!--      名称列-->
      <el-table-column prop="name" label="名称" width="100" />
      <!--      价格列-->
      <el-table-column prop="price" label="价格(元)" width="120" sortable />
      <!--      描述列-->
      <el-table-column prop="description" label="描述" width="250"/>
      <!--      图片列-->
      <el-table-column prop="image" label="图片" width="100" >
        <template #default="scope">
          <img :src="'src/assets/cofferimg/' + scope.row.image" style="width: 80px;height: 80px">
        </template>
      </el-table-column>
      <el-table-column prop="categoryid" label="种类" width="100">
        <template #default="scope">
          <el-tag
              :type="
                scope.row.categoryid === 1
                  ? 'warning'
                  : scope.row.categoryid === 2
                    ? 'success'
                    : 'danger'
              "
              disable-transitions
          >{{
              scope.row.categoryid === 1
                  ? '咖啡'
                  : scope.row.categoryid === 2
                      ? '茶饮'
                      : '甜品'
            }}</el-tag>
        </template>
      </el-table-column>
      <!--      所需原材料及数量-->
      <el-table-column label="原材料及其数量" prop="goods">
        <template v-slot="{ row }">
          <div v-for="(item, index) in row.material" :key="index">
            <p style="font-weight: bold">{{ item.mname }}数量(g)：{{ item.comnum }}</p>
<!--            <p></p>-->
          </div>
        </template>
      </el-table-column>
      <!--      删除编辑列-->
      <el-table-column label="操作">
        <template #default="scope">
          <el-button
              size="small"
              @click="handleEdit(scope.row)"
          >编辑</el-button
          >
          <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
          >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!--    分页功能-->
    <div class="demo-pagination-block">
      <el-pagination
          v-model:current-page="currentPage"
          :page-size="pageSize"
          background
          layout="total, prev, pager, next"
          :total="total"
          @current-change="handleCurrentChange"
      />
    </div>
    <!--表单数据-->
    <el-dialog v-model="dialogFormVisible" :title="dialogTitle" style="width: 420px">
      <el-form :model="tableform">
        <!--        名称-->
        <el-form-item label="名称">
          <el-input v-model="tableform.name" style="width: 300px"/>
        </el-form-item>
        <!--        描述-->
        <el-form-item label="描述">
          <el-input v-model="tableform.description" autosize type="textarea" style="width: 300px"/>
        </el-form-item>
        <!--        图片-->
        <el-form-item label="图片">
          <input type="file" @change="handleFileChange" accept="image/*">
          <!--          <button @click="uploadFile">上传</button>-->
          <!--          <img v-if="tableform.image" :src="tableform.image" alt="上传的图片" style="width: 50px">-->
        </el-form-item>
        <!--        种类-->
        <el-form-item label="种类">
          <el-select v-model="tableform.categoryid" style="width: 300px" placeholder="请选择">
            <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="价格">
          <el-input v-model="tableform.price" style="width: 300px"/>
        </el-form-item>
        <el-form-item label="原材料">
          <div v-for="(material,index) in tableform.material" :key="index" class="mt-4">
            <el-input v-model="material.mname" style="width: 137px" placeholder="名称"></el-input>
            <el-input v-model="material.comnum" style="width: 137px;margin-left: 10px" placeholder="所需数量"></el-input>
            <el-button v-if="index > 0" @click="removeMaterial(index)" type="danger" style="margin-left: 10px">×</el-button>
          </div>
          <el-button @click="addMaterial" type="primary" style="margin-left: 5px;margin-top: 0">+</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit" style="margin-left: 165px">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>

</template>

<script setup lang="ts">
import {getCurrentInstance, computed, reactive, onMounted, ref} from 'vue'
import { Search, FolderChecked, FolderAdd, UploadFilled} from '@element-plus/icons-vue'
import {ElMessage, ElMessageBox, genFileId} from "element-plus";
import axios from "axios";

interface product {
  productid: number
  name: string
  price: number
  description: string
  image: string
  categoryid: number
  goods: Array<{name:string,quantity:number}>
}

const options = [
  {
    value: 1,
    label: '咖啡',
  },
  {
    value: 2,
    label: '茶饮',
  },
  {
    value: 3,
    label: '甜品',
  },
]

//表格数据
const tableData = ref([]);
let currentPage = ref(1); //定义当前页码初始值为1
const pageSize = ref(5); //定义每页显示的数据条数为5
let total = ref(0); //初始化数据总条数

// 使用axios.get()方法获取用户列表
// 在组件挂载后执行回调函数
onMounted(() => {
  getData()
})

// 获取当前页数据
const getData = () => {
  axios.get("http://192.168.166.182:8080/product/getAllProduct",{
    params: {
      pageNo: currentPage.value,
      pageSize: pageSize.value
    }
  }).then(response => {
    console.log(response.data)
    tableData.value  = response.data.records;
    total.value = response.data.total;
  }).catch(error => {
    console.error(error);
  })
}

//页数改变
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  getData()
}

//排序
const handleSortChange = (sortData) => {
  //解构sortData参数，得到prop和order两个属性
  const { prop,order } = sortData;
  //使用sort方法对当前页面数据进行排序，并更新其值
  tableData.value = tableData.value.sort((a,b) => {
    if(order === 'ascending') { //升序
      return a[prop] === b[prop] ? a.productid - b.productid : a[prop] > b[prop] ? 1 : -1;
    } else { //降序
      return a[prop] === b[prop] ? a.productid - b.productid : a[prop] < b[prop] ? 1 : -1;
    }
  });
}

const input = ref('') //初始化搜索输入框
const select = ref('') //初始化搜索选择栏
//搜索框搜查
const filterSearch = (val) => {
  //根据姓名搜索
  if(select.value === "1") {
    //搜索框有输入
    if(val.length > 0) {
      axios.get(`http://192.168.166.182:8080/product/getProductByName`,{
        params: {
          name: val,
          pageNo: currentPage.value,
          pageSize: pageSize.value
        }
      }).then(response => {
        console.log(response.data)
        tableData.value = response.data.records;
        total.value = response.data.total;
      }).catch(error => {
        console.error(error)
      })
    } else { //搜索框无输入
      getData(); //还原表格数据
    }
  } else if(select.value === "2") { //根据编号搜索
    //搜索框有输入
    if(val.length > 0) {
      axios.get(`http://192.168.166.182:8080/product/getProductById`,{
        params: {
          id: val,
          pageNo: currentPage.value,
          pageSize: pageSize.value
        }
      }).then(response => {
        console.log(response.data)
        tableData.value = response.data.records;
        total.value = response.data.total;
      }).catch(error => {
        console.error(error)
      })
    } else { //搜索框无输入
      getData(); //还原表格数据
    }
  } else if(select.value === "3") { // 根据类别查询
    //搜索框有输入
    if(val.length > 0) {
      const shuru = ref();
      if(val === '咖啡') shuru.value = 1;
      else if(val === '甜品') shuru.value = 2;
      else shuru.value =  3;
      axios.get(`http://192.168.166.182:8080/product/getProductByCategory`,{
        params: {
          category: shuru.value,
          pageNo: currentPage.value,
          pageSize: pageSize.value
        }
      }).then(response => {
        console.log(response.data)
        tableData.value = response.data.records;
        total.value = response.data.total;
      }).catch(error => {
        console.error(error)
      })
    } else { //搜索框无输入
      getData(); //还原表格数据
    }
  }
}

const dialogFormVisible = ref(false); //初始化弹窗不显示
const tableform = ref({
  name: '',
  description: '',
  image: '',
  categoryid: '',
  price: '',
  material: [{
    mname: '',
    comnum: ''
  }]
}); //初始化弹窗表单数据
let dialogType = ref('add'); //初始化弹窗类型为增加弹窗
const dialogTitle = computed(() => { //设置弹窗的标题
  return dialogType.value === 'add' ? '新增数据' : '编辑数据';
})
// const file = ref(null);
const handleFileChange = (event) => {
  tableform.value.image = event.target.files[0].name;
  console.log(tableform.value.image);
}
// const uploadFile = async() => {
//   const formData = new FormData();
//   formData.append('file',file.value);
//   try {
//     const response = await axios.post('http://192.168.166.182:8080/api/upload',formData,{
//       headers: {
//         'Content-Type' : 'multipart/form-data'
//       }
//     })
//     tableform.value.image = response.data.url
//   } catch (error) {
//     console.log(error);
//   }
// }

//添加数据按钮事件
const handleAdd = () => {
  dialogFormVisible.value = true;
  dialogType.value = 'add';
  tableform.value = {
    name: '',
    description: '',
    image: '20190830165208_aktvb.jpg',
    categoryid: '',
    price: '',
    material: [{
      mname: '',
      comnum: ''
    }]
  };
}

//编辑数据按钮事件
const handleEdit = (row) => { //row为当前行的数据
  dialogFormVisible.value = true;
  dialogType.value = 'edit';
  tableform.value = {...row};
  tableform.value.image = 'src/assets/cofferimg/' + row.image;
  console.log(row.image);
}

//删除数据方法
const delrow = (row) => { //定义一个函数，用于删除某行数据
  const memberId = parseInt(row.productid);
  // 发送 HTTP DELETE 请求来删除用户
  axios.delete(`http://192.168.166.182:8080/product/deleteByIds`,{
    params: {
      id: memberId
    }
  })
      .then(response => {
        // 处理删除成功后的逻辑，例如重新加载数据
        getData();
      }).catch(error => {
    // 处理错误
    console.error(error)
  })
}

//删除事件
const handleDelete = (row) => {// 处理删除按钮点击事件
  ElMessageBox.confirm(
      '您确定要删除姓名为【' + row.name + '】的数据吗?', '危险操作',
      {confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning',}
  )
      .then(() => {
        delrow(row)
        ElMessage({type: 'success', message: '完成删除！',})
      })
      .catch(() => {
        ElMessage({type: 'info', message: '取消删除!',})
      })
}

let multipleSelection = ref([]); //创建响应式变量，储存当前选中的数据行
//处理表格行选中状态变化的方法，val是当前选中的数据型数组
const handleSelectionChange = (val) => {
  multipleSelection.value = [];
  val.forEach(item => { //遍历选中的数据行数组
    multipleSelection.value.push(item.productid) //将选中的每一行数据加入数组中
  })
}

//批量删除
const handleDelList = () => {
  ElMessageBox.confirm(
      '您确定要删除选择的数据嘛？',
      '危险操作',
      {confirmButtonText:'确定',cancelButtonText:'取消',type:'warning',}
  ).then(() => {
    const memberIds = multipleSelection.value.map(Number);
    console.log(memberIds)
    axios.delete('http://192.168.166.182:8080/product/deletesByIds', {data: memberIds })
        .then(response => {
          // 处理删除成功后的逻辑，例如重新加载数据
          getData();
          ElMessage({type:'success',message:'完成删除！',})
        }).catch(error => {
      console.error(error);
      ElMessage({ type: 'error', message: '删除失败！' });
    });
  }).catch(() => {
    ElMessage({type:'info',message:'取消删除！',})
  })
}

// 添加原材料行
const addMaterial = () => {
  tableform.value.material.push({mname:'',comnum:''});
}

// 删除原材料行
const removeMaterial = (index) => {
  if(tableform.value.material.length > 1 && index > 0) {
    tableform.value.material.splice(index,1);
  }
}

//确定添加数据
const onSubmit = () => {
  dialogFormVisible.value = false;

  if(dialogType.value === 'add') {
    const newMember = {...tableform.value}
    console.log(newMember)
    axios.put('http://192.168.166.182:8080/product/addProduct',newMember)
        .then(response => { // 处理成功响应
          console.log(response)
          if(!response.data) ElMessage({ type: 'error', message: '该商品已存在！请勿重复添加！' });
          else {
            ElMessage({type:'success',message:'添加成功！',})
            getData(); // 在添加数据后调用获取数据的方法
          }
        }).catch(error => { // 处理错误
      console.log(error);
    })
  } else {
    // 创建一个副本来保存更新后的用户信息
    console.log(tableform.value.image.split('/'))
    tableform.value.image = tableform.value.image.split('/')[tableform.value.image.split('/').length - 1];
    const updateMember = {...tableform.value}
    console.log(updateMember)
    // 发送 HTTP PUT 请求来更新用户信息
    axios.post(`http://192.168.166.182:8080/product/changeProduct`,updateMember)
        .then(reponse => {
          // 处理成功响应
          ElMessage({type:'success',message:'修改成功！'})
          // 重新获取数据，更新表格显示
          getData()
        }).catch(error => {
      // 处理错误
      console.error('更新失败！')
      console.error(error)
    })
  }
}


// excel导入导出
const dialogFileVisible = ref(false);
let upload = ref(null);

const handleExceed = (files) => {
  upload.value.clearFiles()
  const file = files[0]
  file.uid = genFileId()
  upload.value.handleStart(file)
}

//导出为excel
const handleExcel = () =>{
  var url = "http://192.168.166.182:8080/product/getProductExcel";
  axios({
    method: 'get',
    url: url,
    responseType: 'blob'
  })
      // axios.get('http://192.168.140.182:8080/student/getExcel')
      .then(res => {
        console.log(res)
        // const link = document.createElement("a");
        // const blob = new Blob([res], {
        //   type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8",
        // });
        // link.style.display = "none";
        // link.href = URL.createObjectURL(blob);
        // link.setAttribute("download", `学生数据.xlsx`);
        // document.body.appendChild(link);
        // link.click();
        // document.body.removeChild(link);
        const content = res.data
        const blob = new Blob([content], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
        const fileName = '商品数据.xlsx'
        if ('download' in document.createElement('a')) { // 非IE下载
          const elink = document.createElement('a')
          elink.download = fileName
          elink.style.display = 'none'
          elink.href = URL.createObjectURL(blob)
          document.body.appendChild(elink)
          elink.click()
          URL.revokeObjectURL(elink.href) // 释放URL 对象
          document.body.removeChild(elink)
        } else { // IE10+下载
          navigator.msSaveBlob(blob, fileName)
        }

      })
      .catch(error => {
        console.error(error);
      });
}

</script>

<style>
.input-with-select .el-input-group__prepend {
  background-color: var(--el-fill-color-blank);
}
.demo-pagination-block {
  margin-top: 10px;
}
.mt-4 {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
}
.bt1 {
  margin-left: 15px;
}
.upload-text {
  margin-top: 20px;
  font-size: 12px;
  color: #999;
}
</style>
